package com.mchat.wsserver;

import com.mchat.wsserver.handler.AuthHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class OnlineUserMap {

    private static final ConcurrentHashMap<Long, ArrayList<Channel>> USER_MAP = new ConcurrentHashMap<>();

    /**
     * 在线用户的channel映射，允许多设备同时在线
     */
    public static void add(Long uid, Channel channel) {
        // 使用compute方法保证原子性操作
        USER_MAP.compute(uid, (k, pairList) -> {
            if (pairList == null) {
                // 如果不存在，创建新的列表
                ArrayList<Channel> list = new ArrayList<>(3);
                list.add(channel);
                return list;
            } else {
                pairList.add(channel);
                return pairList;
            }
        });

    }
    public static void remove(Long key, Channel channel) {
        USER_MAP.computeIfPresent(key, (k, existingList) -> {
            existingList.remove(channel);
            // 如果列表为空，返回null会自动移除该键值对
            return existingList.isEmpty() ? null : existingList;
        });
    }
    public static ArrayList<Channel>get(Long key){
        return USER_MAP.get(key);
    }

}
